package com.reconcile.phone.web.controller.call;


import cn.hutool.core.util.ObjectUtil;
import com.reconcile.phone.common.annotation.Log;
import com.reconcile.phone.common.core.controller.BaseController;
import com.reconcile.phone.common.core.domain.R;
import com.reconcile.phone.common.enums.BusinessType;
import com.reconcile.phone.common.enums.OperatorType;
import com.reconcile.phone.system.domain.vo.SysOssVo;
import com.reconcile.phone.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 小程序-文件上传
 *
 * @author shichunjie
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/supermarket/mobile/oss")
public class OssController extends BaseController {

    private final ISysOssService iSysOssService;



    /**
     * 上传OSS对象存储
     *
     * @param file 文件
     */
    @Log(title = "移动端OSS对象存储", businessType = BusinessType.INSERT,operatorType = OperatorType.MOBILE)
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String, String>> upload(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            return R.fail("上传文件不能为空");
        }
        SysOssVo oss = iSysOssService.upload(file);
        Map<String, String> map = new HashMap<>(2);
        map.put("url", oss.getUrl());
        map.put("fileName", oss.getOriginalName());
        map.put("ossId", oss.getOssId().toString());
        return R.ok(map);
    }

    /**
     * 下载OSS对象
     *
     * @param ossId OSS对象ID
     */
    @Log(title = "移动端下载OSS对象", businessType = BusinessType.DOWNLOAD,operatorType = OperatorType.MOBILE)
    @GetMapping("/download/{ossId}")
    public void download(@PathVariable Long ossId, HttpServletResponse response) throws IOException {
        iSysOssService.download(ossId,response);
    }

    /**
     * 删除OSS对象存储
     *
     * @param ossIds OSS对象ID串
     */
    @Log(title = "移动端OSS对象存储", businessType = BusinessType.DELETE,operatorType = OperatorType.MOBILE)
    @GetMapping("/{ossIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ossIds) {
        return toAjax(iSysOssService.deleteWithValidByIds(Arrays.asList(ossIds), true));
    }

}
